import aiohttp
import asyncio
import time
import ssl

# 禁用SSL验证（根据实际情况决定是否启用）
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Origin': 'http://59.215.206.188',
    'Referer': 'http://59.215.206.188/tyspzy//approval/systemsetting/call/compensationPush?v=1759023909218',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    'Cookie': 'JSESSIONID=0DC2F43DD9D675FF43B6E20228AD6AA6; '
}


async def query(session):
    """异步查询需要重发的BSNUM列表"""
    data = {
        '_search': 'true',
        'nd': int(time.time() * 1000),
        'rows': '5000',
        'page': '1',
        'sidx': 'CALL_TIME',
        'sord': 'desc',
        'receiveNumber': '',
        'applySubject': '',
        'start': '2025-09-01',
        'orgCode': '',
        'end': '2025-09-28',
        'type': 'cloudFinish',
    }

    async with session.post(
            'http://59.215.206.188/tyspzy/approval/systemsetting/call/compensationPushQuery',
            data=data,
            ssl=ssl_context
    ) as response:
        result = await response.json()
        return [item['cell']['BSNUM'] for item in result['rows']]


async def resend(session, bs_num):
    """异步重发单个请求"""
    params = {'method': 'compensationRePush'}
    data = {
        "id": "undefined",
        "type": "CLOUDFINISH",
        "bsNum": bs_num,
        "state": "NONE",
        "callId": ""
    }

    async with session.post(
            'http://59.215.206.188/tyspzy/approval/systemsetting/call',
            params=params,
            json=data,
            ssl=ssl_context
    ) as response:
        text = await response.text()
        print(text)


async def main():
    # 创建异步会话（复用连接）
    async with aiohttp.ClientSession(headers=headers) as session:
        # 获取任务列表
        task_list = await query(session)
        print(f"获取到 {len(task_list)} 个任务")

        # 并发执行所有重发任务（控制并发量为10，避免请求过于密集）
        semaphore = asyncio.Semaphore(10)

        async def bounded_resend(bs_num):
            async with semaphore:  # 限制并发数
                await resend(session, bs_num)

        # 批量创建任务并等待完成
        await asyncio.gather(*[bounded_resend(bs_num) for bs_num in task_list])


if __name__ == '__main__':
    # 运行异步主函数
    asyncio.run(main())
